package org.hbhk.hms.job;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.hbhk.aili.job.annotation.JobConfig;
import org.hbhk.hms.entity.HmsShard;
import org.hbhk.hms.mapper.HmsShardMapper;
import org.hbhk.hms.mq.MqProvider;
import org.hbhk.hms.mq.MqSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;

/**
 * 
 * 根据topic定时推送mq，进行消费处理，对应的topic未触发数据
 *
 */
@JobConfig(name = "HmsTopicJob", cron = "0/3 * * * * ?", description = "根据topic定时推送mq，进行消费处理，对应的topic未触发数据")
public class HmsTopicJob implements SimpleJob, InitializingBean {

	Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private HmsShardMapper hsmShardMapper;

	@Value("${mq.subscribe.HmsDelay:HmsDelay}")
	private String subscribe = "HmsDelay";
	List<HmsShard> hmsTopicList;

	public void execute(ShardingContext context) {
		log.info("HmsTopicJob");
		if (hmsTopicList != null) {
			for (HmsShard hmsMq : hmsTopicList) {
				log.error("触发业务场景:" + hmsMq.getShard());
				hmsMq.setCreateTime(new Date());
				hmsMq.setUpdateTime(null);
				hmsMq.setId(null);
				hmsMq.setStatus(null);
				MqSender.sendMessage(hmsMq.getShard(), JSON.toJSONString(hmsMq), MqProvider.hmsDelayMq, subscribe);
			}
		}
	}

	ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

	@Override
	public void afterPropertiesSet() throws Exception {
		executor.scheduleAtFixedRate(new Runnable() {

			@Override
			public void run() {
				log.info("load  mq shard ");
				QueryWrapper<HmsShard> queryWrapper = new QueryWrapper<>();
				queryWrapper.eq("status", 1);
				hmsTopicList = hsmShardMapper.selectList(queryWrapper);
			}
		}, 0, 3, TimeUnit.MINUTES);

	}

}
